package com.archgeek.java.udp.v1simple;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * 服务提供方
 *
 * @author pizhihui
 * @date 2023-03-03
 */
public class UDPProvider {

    public static void main(String[] args) {
        System.out.println("UDPProvider Started...");

        DatagramSocket ds = null;
        try {
            // 监听的 20000 端口
             ds = new DatagramSocket(20000);

            final byte[] buf = new byte[512];
            DatagramPacket receivePack = new DatagramPacket(buf, buf.length);

            // 接收消息
            System.out.println("UDPProvider waiting msg......");
            ds.receive(receivePack);
            System.out.println("UDPProvider received msg......receivePack=" + receivePack);


            String ip = receivePack.getAddress().getHostAddress();
            int port = receivePack.getPort();
            int dataLen = receivePack.getLength();
            String data = new String(receivePack.getData(), 0, dataLen);
            System.out.println("UDPProvider receive from ip: " + ip + ",port:" + port + ",data:" + data);

            // 构建一份回送数据
            String responseData = "Receive data with len:" + dataLen;
            byte[] responseDataByte = responseData.getBytes();
            DatagramPacket responsePacket = new DatagramPacket(responseDataByte, responseDataByte.length,
                    receivePack.getAddress(), receivePack.getPort());
            ds.send(responsePacket);

            System.out.println("UDPProvider Finished!");
        } catch (SocketException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            if (null != ds) {
                ds.close();
            }
        }


    }


}
